package com.yun.zf.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.ZfHouseDetailMapper;
import com.yun.zf.admin.service.ZfHouseDetailService;
import com.yun.zf.admin.service.ZfHouseScoreService;
import com.yun.zf.admin.util.ReflectionObjectUtil;
import com.yun.zf.common.admin.model.house.HouseDetailMo;
import com.yun.zf.common.app.domain.ZfCity;
import com.yun.zf.common.app.domain.ZfHouseDetail;
import com.yun.zf.common.app.domain.ZfHouseScore;
import com.yun.zf.common.mapstruct.admin.HouseMapper;
import com.yun.zf.system.service.ZfCityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 房源表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-01-29
 */
@Service
@Slf4j
public class ZfHouseDetailServiceImpl extends ServiceImpl<ZfHouseDetailMapper, ZfHouseDetail> implements ZfHouseDetailService {
    @Autowired
    private ZfHouseScoreService scoreService;
    @Autowired
    private ZfHouseDetailMapper houseDetailMapper;
    @Autowired
    private ZfCityService cityService;
    @Autowired
    private ReflectionObjectUtil objectUtil;

    /**
     * 补充房源信息
     *
     * @param house
     */
    @Override
    @Transactional
    public int addHouseDetailInfo(HouseDetailMo house, int type, Long provCode, Long cityCode) {
        ZfHouseDetail houseDetail = HouseMapper.INSTANCE.moToHouseDetail(house);
       houseDetail.setCityCode(cityCode);
       houseDetail.setProvinceCode(provCode);
        //2、 查询城市简称
        ZfCity city = cityService.getCity(cityCode);
        // 3、设置房源编号
        houseDetail.setHouseNumber(city.getAbbreviation() + houseDetail.getBasicId());
        // 如果是出售房源设置单价
        if (type == 1) {
            houseDetail.setPriceUnit("元");
        } else if (type == 2) {
            houseDetail.setPriceUnit("万元");
            BigDecimal average = houseDetail.getExhaustPrice().divide(houseDetail.getArea(), 0, BigDecimal.ROUND_HALF_UP);
            houseDetail.setAveragePrice(average);
        }
        //1、楼层计算
        double avg = Math.ceil(house.getTotalFloor() / 5);
        String floorTag = "";
        BigDecimal floorScore = new BigDecimal("0");
        if (house.getFloor() * 2 <= avg) {
            floorTag = "bottom";
            floorScore = new BigDecimal("0.3");
        } else if (house.getFloor() > avg * 0.5 && house.getFloor() <= avg * 1.5) {
            floorTag = "low";
            floorScore = new BigDecimal("0.6");
        } else if (house.getFloor() > avg * 1.5 && house.getFloor() <= 3 * avg) {
            floorTag = "middle";
            floorScore = new BigDecimal("0.8");
        } else if (house.getFloor() > 3 * avg && house.getFloor() <= house.getTotalFloor() - 1) {
            floorTag = "high";
            floorScore = new BigDecimal("0.9");
        } else if (house.getFloor() == house.getTotalFloor()) {
            floorTag = "top";
            floorScore = new BigDecimal("0.3");
        }
        houseDetail.setFloorTag(floorTag);
        // 先查询是否存在，不存在则添加，存在则进行修改
        QueryWrapper<ZfHouseDetail> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ZfHouseDetail::getBasicId,houseDetail.getBasicId()).eq(ZfHouseDetail::getCityCode,cityCode)
                .eq(ZfHouseDetail::getProvinceCode,provCode);
       ZfHouseDetail dl = baseMapper.selectOne(wrapper);
       int count=0;
       if (dl==null){
           houseDetail.setCreateTime(new Date());
            count = baseMapper.insert(houseDetail);
       }else {
           BeanUtil.copyProperties(houseDetail, dl, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
         count =  baseMapper.update(dl,wrapper);
       }

        // 计算房源分数以及信息完成度
        if (count > 0) {
            BigDecimal detail = objectUtil.checkIsNull(houseDetail, "com.yun.zf.common.app.domain.ZfHouseDetail");
            log.info("房源信息完成度计算得分-----{}", detail.toString());
            calculateScore(house.getIsElevator(), floorScore, detail, house.getBasicId(), cityCode, provCode);
        }
        return count;
    }

    @Override
    public HouseDetailMo getHouseDetai(Long houseId, Long provCode, Long cityCode) {
        return baseMapper.getDetail(houseId,provCode,cityCode);
    }

    /**
     * 计算得分
     *
     * @param basicId
     * @param cityCode
     * @param provCode
     * @return
     */
    public void calculateScore(Integer isElevator, BigDecimal floorScore, BigDecimal detail, Long basicId, Long cityCode, Long provCode) {
        // 电梯权重占30%， 楼层占70%(其中底层10%，低层20%,中楼层25%，高楼层30%，顶层15% )
        ZfHouseScore houseScore = new ZfHouseScore();
        BigDecimal score = new BigDecimal("0");
        // 推荐权重占30%
        if (isElevator == 0) {
            score = new BigDecimal("3");
        }
        BigDecimal floor = new BigDecimal("7").multiply(floorScore);
        houseScore.setDetailScore(score.add(floor));
        houseScore.setDetail(detail);
        houseScore.setBasicId(basicId);
        houseScore.setCityCode(cityCode);
        houseScore.setProvinceCode(provCode);
        // 更新房源分数
        scoreService.addOrUpdate(houseScore);

    }
}
